package com.boyi.shared.util.http.impl;


import com.boyi.shared.util.http.HttpUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 同步http
 *
 * @author 颜培轩
 * @date 2017年11月18日 下午 12:56
 */
public class SyncHttpRequset extends HttpRequest implements HttpUtil {

    private static Log logger = LogFactory.getLog(SyncHttpRequset.class);

    public SyncHttpRequset() {
        super();
    }

    public SyncHttpRequset(Map mapHeader) {
        super(mapHeader);
    }

    public SyncHttpRequset(String charset, String contentType) {
        super(charset, contentType);
    }

    public SyncHttpRequset(String charset, String contentType, Map mapHeader) {
        super(charset, contentType, mapHeader);
    }

    public SyncHttpRequset(String charset, String contentType, int protocolTimeoutMS, int connectTimeoutMS) {
        super(charset, contentType, protocolTimeoutMS, connectTimeoutMS);
    }

    public SyncHttpRequset(String charset, String contentType, int protocolTimeoutMS, int connectTimeoutMS,
                           Map mapHeader) {
        super(charset, contentType, protocolTimeoutMS, connectTimeoutMS, mapHeader);
    }

    /**
     * @param port eg: 80
     * @param ip   eg: ""
     * @author 颜培轩
     * @date 2017/11/18
     */
    @Override
    public HttpResponse post(String ip, int port) {
        return this.post(ip, port, null);
    }

    @Override
    public HttpResponse post(String ip, int port, String uri, String username, String password) {
        return this.post(ip, port, uri, username, password, null);
    }

    @Override
    public HttpResponse post(String ip, int port, String uri) {
        return this.post(ip, port, uri, null);
    }

    @Override
    public HttpResponse post(String ip, int port, String uri, Map parameters) {
        return this.post(ip, port, uri, null, null, parameters);
    }

    @Override
    public HttpResponse post(String ip, int port, String uri, String username, String password, Map parameters) {

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(protocolTimeoutMS)
                .setConnectTimeout(connectTimeoutMS).build();// 设置请求和连接超时时间

        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        CloseableHttpResponse response = null;
        // 设置Http Post数据
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (parameters != null) {
            parameters.forEach((o, v) -> {
                nvps.add(new BasicNameValuePair(String.valueOf(o),String.valueOf(v)));
            });
        }

        HttpEntityEnclosingRequestBase httpData = new HttpPost(uri);
        httpData.addHeader("Content_type", "application/json;charset=utf-8");

        try {
//        StringEntity s = buildStringEntity(parameters);
        httpData.setEntity(new UrlEncodedFormEntity(nvps, charset));
        buildHeader(httpData);

        HttpHost httpHost = new HttpHost(ip, port);
        HttpClientContext context = HttpClientContext.create();

        if (username != null) {
            CredentialsProvider credsProvider = setAuthentication(username, password, httpHost);
            context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);
        }
            response = httpClient.execute(httpHost, httpData, context);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        }
        return response;
    }

    @Override
    public HttpResponse get(String ip, int port) {
        return this.get(ip, port, null);
    }

    @Override
    public HttpResponse get(String ip, int port, String uri) {
        return this.get(ip, port, uri, null, null);
    }

    @Override
    public HttpResponse get(String ip, int port, String uri, String username, String password) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        HttpGet httpGet = new HttpGet(uri);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(protocolTimeoutMS)
                .setConnectTimeout(connectTimeoutMS).build();// 设置请求和连接超时时间
        httpGet.setConfig(requestConfig);

        buildHeader(httpGet);

        HttpHost httpHost = new HttpHost(ip, port);
        HttpClientContext context = HttpClientContext.create();

        if (username != null) {
            CredentialsProvider credsProvider = setAuthentication(username, password, httpHost);
            context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);
        }

        try {
            response = httpClient.execute(httpHost, httpGet, context);
            System.out.println("response = " + response.getStatusLine().getStatusCode());
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        }
        return response;
    }

}
